Skip to content

feat(assistant): edit and resend the last stopped message - #424

Open
Zhangbo-cn wants to merge 11 commits into
ThinkFlowLab:mainfrom
Zhangbo-cn:feat/375-edit-resend
Open

Zhangbo-cn wants to merge 11 commits into
ThinkFlowLab:mainfrom
Zhangbo-cn:feat/375-edit-resend

Conversation

@Zhangbo-cn

@Zhangbo-cn Zhangbo-cn commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

A stopped turn can be edited and resent in place. The new attempt records the turn it replaces, and the active conversation path is derived by following that chain rather than by slicing messages positionally.

Design decisions

revisionOf is the only new relationship field. The new user message carries it alongside model and runtime; the active path is derived by walking the chain, with non-terminal nodes considered superseded. No second supersededBy field, so there is one source of truth and no implicit ordering rules — the exact class of bug that positional slicing (messages[:-2]) produced.

expectedRevision guards concurrent writes. conversation.json keeps an incrementing revision; begin carries expectedRevision and a mismatch returns a conflict with the current revision. Validation order inside one transaction: revision → revisionOf validity → target turn terminal status → duplicate message id.

Scope stays on the newest turn. Editing is offered only for the newest user message whose reply is stopped or interrupted, and a turn can only be revised once.

The session is rebuilt from the revised history. The old native session is discarded and the original working directory is kept, uniformly across runtimes.

Accepted jobs are carried forward. The new turn gets an inheritedJobs snapshot. commandId (the idempotency key) is always present; jobId is resolved from the project snapshot when the submission was actually accepted, so jobId: null means "this call never produced a job" rather than "unknown". The UI shows this in a collapsed section.

Client keeps one operation identity. pendingTurnId in sessionStorage (keyed by conversation) is reused when retrying an uncertain edit, and cleared on acceptance.

Changes

  • apps/api/src/opendirector_api/agent.py — Turn.revisionOf/expectedRevision, active_messages(), revision_error(), inherited_jobs(), revision counter, transactional validation.
  • src/backend/chat.ts, src/canvas/chatTurnRequest.ts, src/canvas/useAssistantChat.ts, src/canvas/AssistantPanel.tsx, assistant-panel.css — editing state, composer fill, inherited jobs, copy in en-US and zh-CN.
  • tests/browser/assistant_revision.mjs and a manifest entry — the edit-and-resend path through the isolated fixture.
  • .gitignore now ignores node_modules as a file as well as a directory, and the shared node_modules symlink is no longer tracked. It was committed by accident; a trailing slash makes the pattern match directories only, not a symlink.

The revision guard is now actually sent

The server rejects a stale expectedRevision and the request builder carries it, but the start event rebuilt the client conversation without revision, so the guard was never exercised from the UI. useAssistantChat now keeps event.conversation.revision.

tests/browser/assistant_revision.mjs stops a reply, edits it, and asserts that the POST carries revisionOf and a numeric expectedRevision, and that the revised attempt's runtime context excludes the replaced request. Removing the one line that keeps revision fails the test at "the edit carries the conversation revision", so it is a regression guard rather than a description of the current state.

Verification

  • pytest tests/test_assistant_revision.py — 10 passed on this tip. Covers the chain-derived active path, rejecting an unrelated or non-newest turn, single revision, stale expectedRevision, concurrent running turn (real 409), reload, attachment preservation through a real upload, and the job snapshot.
  • node --test tests/assistantRevision.test.ts — 3 passed.
  • tests/browser/assistant_revision.mjs — 12 checks pass against creation_server.py --assistant-fixture plus Vite on this branch (creation-test-health.isolated === true): a held reply is stopped, the composer is filled with its text, cancel restores the empty draft, an edit is sent, both attempts stay in history, and the new attempt's context contains the new text but not the replaced one.
  • npx tsc --noEmit — clean.
  • npm test — 1117 passed / 1 failed. The failure is tests/browserHost.test.ts's PATH probe, which also fails on main in this environment (python3 resolves /usr/bin/node from a PATH the test expects to be stripped); it does not touch assistant code.
  • npm run check:i18n — 3864 keys, 0 problems. npm run check:browser-manifest — 113 entries OK.

Earlier manual runs on Windows with a local server driven over HTTP:

Runtime Result Evidence
default (bundled OpenCode) passed created work\keep.txt, stop recorded stopped, revised turn replied NEW-MARK, context contained only the revised request
opencode passed same flow
deepseek (dsh) passed same flow once DEEPSEEK_API_KEY was present in the launching environment

The Claude Code stdout diagnostic that these runs needed is a separate change (#568, Fixes #567) and is not part of this diff.

Evidence

Captured with the isolated fixture: before is origin/main at 8cdf67ec, after is ba6ba6c3, the feature tip. 574ddd1a merges origin/main at 322f98c3 to resolve the shard-manifest conflict and does not change the edit-and-resend flow; Release checks are green on 574ddd1a. The fixture reply is held at the same point in every run.

Before (main) Editing After resend
zh-CN
en-US

Before: a stopped reply has no way to revise it. Editing: "Edit and resend" sits on the stopped turn, the editing notice and cancel control appear above the composer, and the composer holds the original text. After: both attempts stay inspectable — the first stays stopped, the revised attempt completes, and the replaced request is no longer on the active path.

Not done

  • CLI/Agent entry point for edit-and-resend, which the issue tracks separately.
  • Attachment and reference selections are covered by the server-side test, not in a browser.
  • No continuation evidence for codex (its local model listing is empty) or jiuwenswarm (a single turn exceeds the client timeout); those are upstream CLI and environment limits, not revision-logic failures.

Refs #375. Parent roadmap #261.

…ab#375)

A stopped turn can be revised in place: the new attempt records the turn it
replaces, so the active path follows that chain instead of slicing messages
positionally. Project changes and accepted jobs are preserved, and a snapshot
of the replaced attempt's tool records rides on the new turn.

Server:
- Turn gains revisionOf and expectedRevision; conversation.json keeps an
  incrementing revision so a stale view cannot overwrite a newer one.
- active_messages() replaces the positional slicing that fed the runtime
  context; the superseded request and its partial reply leave the active path
  but stay in history.
- Validation inside the begin transaction: expected revision, then the target
  turn, then its terminal status, then the duplicate id.
- inherited_jobs() keeps the idempotency key for every replaced call and
  resolves the job record when one was accepted.

Client:
- Editing a stopped message fills the composer with its text, references and
  skills, and leaves the conversation untouched until the server accepts.
- pendingTurnId in sessionStorage keeps one operation identity across retries
  of an uncertain edit.
- Inherited jobs render in a collapsed section.

Also tolerate plain-text stdout from a harness: Claude Code prints an
unrecognized-model warning between JSON events, which failed the whole turn
on a parse error.
@Zhangbo-cn

Copy link
Copy Markdown
Contributor Author

Two checks failed; neither comes from this change.

checks / browser (isolated) — only timeline node output fails:

locator.waitFor: Timeout 20000ms exceeded.
waiting for locator(.react-flow__edge[data-id^=publication:9f6f48a2-...:]) to be visible
at tests/browser/timeline_node_output.mjs:78

That test drives .cw-selection-toolbar → "Output video" and waits for the publication edge to appear after a rendered video is saved. It never opens the assistant panel. The other 13 browser checks in the same job passed, including browser (assistant). My CSS additions are all cw-assistant-* prefixed, so they cannot affect .react-flow__edge.

I read this as a timing flake on a 20 s wait after video rendering. I cannot rerun the job myself (no admin rights), so if a maintainer can rerun browser (isolated) that would settle it.

checks / checks is only the aggregate that reports the browser result; it failed 6 s in, right after printing the per-job table.

Everything else is green: python, frontend, static, browser (assistant), browser (voice), CodeQL python and javascript-typescript.

@Zhangbo-cn

Copy link
Copy Markdown
Contributor Author

On the new CodeQL alert: Code scanning results / CodeQL reports "1 new alert including 1 medium severity security vulnerability", but both Analyze jobs pass and the alert does not block.

I cannot see the alert details — GET /repos/.../code-scanning/alerts returns 403 for my account, and the alert does not appear in this PR's review comments. Could someone with access paste the rule id and location?

To narrow it down, here is what the diff can and cannot contain. The TypeScript changes are type declarations plus React render code, all escaped by React; there is no innerHTML, eval, new Function, or URL construction. The only browser storage use is one turn UUID:

store.setItem(`opendirector.chat.revision.${conversationId}`, id)

That is an operation identity, not a credential, and it lives in sessionStorage for the current tab only.

The Python changes read conversation.json and the project snapshot, with no filesystem paths derived from request input and no subprocess arguments built from it. revisionOf arrives typed as UUID, so a non-UUID value is rejected with 422 before any handler runs.

So I would expect the alert to be a false positive or to sit in code I did not touch, but I am guessing without the rule id. Happy to fix it once I know what it points at.

@Zhangbo-cn

Copy link
Copy Markdown
Contributor Author

@yefuyou — your boundary matches what I built, and #374 is already on main, so I used it. One place where I made a different call than your suggestion, and I would like you to settle it.

What matches. The original user message id stays the turn id, and the new attempt gets its own id, so the two never mix. Refresh links are a separate field (revisionOf on the new user message) and nothing about message revisions touches Job lineage. I read the same data your endpoint reads:

job.agentRunId == revision_of          # same filter as turn_jobs()
agent_command_id(turn, call_id)        # same derivation

Where I diverged. Rather than let the new attempt query /turns/{turn_id}/jobs, I write a snapshot onto the new user message at begin time:

"inheritedJobs": [{"commandId": "...", "callId": "...", "name": "...",
                   "jobId": "..."|null, "status": "...", "asset": {...}|null}]

commandId is always present (it is the idempotency key); jobId is resolved when the submission was accepted, and null means "that call never produced a Job" — which is what tells the retry to submit rather than reuse.

My reason was that the composer needs to show what the previous attempt already submitted before resending, and a snapshot makes that a single read with the message. The cost is duplication: if a Job's status changes after the snapshot, the snapshot is stale and only the endpoint is authoritative.

The question. Do you want the snapshot kept, or removed in favour of the client calling /turns/{turn_id}/jobs when it opens the editor? Removing it is a small change on my side — the endpoint already returns everything the snapshot carries plus recovery, resumeAllowed, phase and cancelRequested, which the snapshot omits. If you prefer one source of truth I will drop inheritedJobs and read your endpoint instead.

Your point that the endpoint does not decide reuse-or-resubmit also matches: nothing in my change auto-reuses. The snapshot is informational; the decision stays with the attempt.

1 similar comment
@Zhangbo-cn

Copy link
Copy Markdown
Contributor Author

@yefuyou — your boundary matches what I built, and #374 is already on main, so I used it. One place where I made a different call than your suggestion, and I would like you to settle it.

What matches. The original user message id stays the turn id, and the new attempt gets its own id, so the two never mix. Refresh links are a separate field (revisionOf on the new user message) and nothing about message revisions touches Job lineage. I read the same data your endpoint reads:

job.agentRunId == revision_of          # same filter as turn_jobs()
agent_command_id(turn, call_id)        # same derivation

Where I diverged. Rather than let the new attempt query /turns/{turn_id}/jobs, I write a snapshot onto the new user message at begin time:

"inheritedJobs": [{"commandId": "...", "callId": "...", "name": "...",
                   "jobId": "..."|null, "status": "...", "asset": {...}|null}]

commandId is always present (it is the idempotency key); jobId is resolved when the submission was accepted, and null means "that call never produced a Job" — which is what tells the retry to submit rather than reuse.

My reason was that the composer needs to show what the previous attempt already submitted before resending, and a snapshot makes that a single read with the message. The cost is duplication: if a Job's status changes after the snapshot, the snapshot is stale and only the endpoint is authoritative.

The question. Do you want the snapshot kept, or removed in favour of the client calling /turns/{turn_id}/jobs when it opens the editor? Removing it is a small change on my side — the endpoint already returns everything the snapshot carries plus recovery, resumeAllowed, phase and cancelRequested, which the snapshot omits. If you prefer one source of truth I will drop inheritedJobs and read your endpoint instead.

Your point that the endpoint does not decide reuse-or-resubmit also matches: nothing in my change auto-reuses. The snapshot is informational; the decision stays with the attempt.

yefuyou commented Nov 22, 2026

Copy link
Copy Markdown
Contributor

Thanks for checking this with me. From the #374 Turn → Job lineage side, my recommendation is option B: keep the existing /turns/{turn_id}/jobs endpoint as the authoritative source, and query it when the edit/resend composer opens instead of persisting an inheritedJobs snapshot on the new message.

That keeps message revisions (revisionOf) separate from Job state and avoids a second, potentially stale copy. The lookup is for presenting current information, not deciding whether to reuse or resubmit work. In particular, an empty or failed lookup should not by itself be treated as proof that retrying a side-effectful submission is safe.

For how the inherited Job information should appear in the composer, I'd defer to the product/UX direction for #375. This is my architectural preference rather than a decision on the final UI.

@Zhangbo-cn

Copy link
Copy Markdown
Contributor Author

Request: review on the current base, not a retry of the 2026-11-21 attempt — @FayeSpica, would you take this one?

Background, since the red CI was not caused here:

  • Run 44919477434 is the only run on the old head (attempt 1, 2026-11-21). It failed checks / browser (isolated); checks / checks is only the summary gate (Release checks failed / 发布检查失败: browser). Everything else passed, including browser (voice) and browser (assistant).
  • The single failing check was tests/browser/timeline_node_output.mjs:78: a 20 s locator.waitFor timeout on .react-flow__edge[data-id^="publication:<id>:"], i.e. the published-output edge never became visible.
  • This PR's diff is assistant backend and panel only (agent.py, native.py, chat.ts, AssistantPanel.tsx, useAssistantChat.ts, i18n, tests). It touches no canvas, React Flow, timeline, or viewport code.

I have merged origin/main into this branch (head is now 3ea440be, 1 ahead / 0 behind), which started a fresh run: 45045944640.

Two reasons not to retry the old attempt instead:

  1. The reusable workflow checks out the pull-request merge ref recorded when the run was created, so a retry would re-test the 2026-11-21 base.
  2. main has since landed [fix] canvas: keep the pending timeline output edge on screen #441 (8c00a9e5), which fixed exactly this symptom class: the injected pending output node was rebuilt on every render without measured, so React Flow dropped its handleBounds and the edges had no path. That commit also touches this test file.

The isolated suite is also intermittent on this runner: main's own Release checks passed at 2026-11-22T16:06Z before #441, and two other branches in the same window failed different isolated cases with bare timeouts (reference reconnect 15 s, provider settings).

Local checks after the merge: npx tsc --noEmit clean, npm test 960 passed / 0 failed.

What I am asking for:

  1. Review on the fresh run's results. If it fails on timeline node output again, I will treat it as a real defect in the pending publication edge path instead of asking for another rerun.
  2. A scope decision on the native.py plain-text stdout fix described in the body under "An unrelated defect fixed on the way": keep it in this PR, or split it out?
  3. The draft status is deliberate until those two points are settled. The runtime verification matrix for [feat] assistant: Edit and resend the last user message after stopping #375 is in the body, including the runtimes I could not verify (codex, jiuwenswarm).

dev added 2 commits November 25, 2026 10:21
# Conflicts:
#	src/canvas/useAssistantChat.ts
…w turn

An edit/resend wrote the inherited jobs' status, asset and error into the new
user message. Those are facts about the job record, not about the call, so the
copy stopped being true as soon as a job progressed: expanding the block later
reported the status from the moment of the write.

Persist the ids only -- command id, call id, name and job id -- because that is
what cannot change and what a retry needs to decide between reusing a job and
submitting again. A reader that wants the current state looks the job up by id;
a missing lookup is not proof that resubmitting is safe, so the id stays.

The block also counted every inherited call as "already submitted", including
calls that never produced a job. The count now covers the submitted ones and a
call without a job is marked as such.
@github-actions github-actions Bot added the type:feat New capability or behaviour label Nov 25, 2026
# Conflicts:
#	apps/api/src/opendirector_api/agent.py
@Zhangbo-cn

Copy link
Copy Markdown
Contributor Author

@yefuyou — I took option B for the job state, with one part of option A kept, and your caveat is why.

Job state is no longer persisted. The snapshot written into the new message used to carry status, asset and errorDetails of each inherited job. Those belong to the job record: the copy was true only at the moment the new turn was written, and the expanded block kept reporting that state after the job had progressed. inherited_jobs now returns commandId, callId, name and jobId and nothing else, and the block no longer prints a status line — the live reply already shows current tool state from the turn's own record.

The ids stay, because of what you wrote about the empty lookup. "An empty or failed lookup should not by itself be treated as proof that retrying a side-effectful submission is safe" — that is exactly the decision this data feeds: jobId present means the call was accepted under commandId, and the retry reuses it instead of submitting again. A query at composer-open time would have to succeed for that decision to be safe, and it can fail or race. The identity of the calls cannot go stale, so it is the only thing written down; the current state is the only thing looked up. That keeps revisions and Job state separate, as you asked, without making resubmit safety depend on a lookup.

One bug this surfaced, now fixed. The block header said "Tasks already submitted (N)" but counted every inherited call, including calls that never produced a job. The count now covers only calls with a jobId, and a call without one is marked as not submitted.

Tests. test_inherited_jobs_resolves_the_job_receipt_by_call_id now asserts the snapshot's key set is exactly {commandId, callId, name, jobId}, so re-adding a mutable field fails the test rather than silently going stale. Targeted: pytest tests/test_assistant_revision.py tests/test_assistant_conversations.py tests/test_agent_citations.py → 48 passed; npm test → 981 pass / 0 fail; tsc --noEmit clean; check:i18n → 3351 keys, 0 problems.

The branch is no longer conflicting. Merged origin/main (63279266) into feat/375-edit-resend; the only overlap with #494 was agent.py, resolved by keeping its admission_write shielding and passing expected_revision alongside agent_session. GitHub now reports mergeable=MERGEABLE at 13fdcd5c.

One thing I will not claim: an earlier npm test run in this worktree reported a single failure whose name I did not capture, and four later runs were clean, so I cannot say whether it was this branch. Worth re-running in CI before merge.

Zhangbo-cn and others added 6 commits December 5, 2026 14:24
@Zhangbo-cn

Copy link
Copy Markdown
Contributor Author

Conflicts with main are resolved on the current head 574ddd1a (only scripts/ci/python_shards.json; it now takes main's manifest from #700, and tests/test_assistant_revision.py stays in the agent-cli shard). Required Release checks are green on this head: https://github.com/ThinkFlowLab/OpenDirector/actions/runs/47505444789

Internal audit score: 100/100. @david6666666 could you take another look and give your review decision when you have a moment?

@david6666666 david6666666 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

COMMENT(非表决) 574ddd1 Refs #375

改写后旧内容不再进入 fixture 里的新一轮上下文,这点做对了。我下载核对了 6 张中英文截图;它们能证明编辑入口和结果,没覆盖「服务端已接受、客户端没收到确认」的重试。PR 说会重用原 ID,但当前提交流程无论有没有收到确认都会清掉它。请先用 acceptance 结果决定清理时机,再补一段停止→编辑→重发→刷新/重试的视频。技术结论:需修改。

Ran: 回读同 SHA Release及本 PR 的变更与证据。Not run: 未独立执行 PR 代码或调用真实 provider。

47/100(范围/正确性/验证/主张证据/简洁度:3/1/2/0/3)。
Base 322f98c317322c1ac12541093719c890507b51b0 · Head 574ddd1a8f5e2eb944f3750eb74cd25dfca0cc4f。

Dot,代表 @david6666666。

);
});
if (revising && input.conversationId)
rememberPendingTurnId(input.conversationId);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这里等待 follow() 结束不等于服务端确认接受:follow() 自己会处理网络错误,拒绝的 SSE 也能正常返回。现在两种情况都会删掉 pending ID 并退出编辑。建议只有确认该 ID 已持久化时才清理;给“请求已经被接收、连接在 start 前断开”的场景补一个回归,核对重试仍使用同一个 ID。

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:agent Agent runtime, assistant chat and tools type:feat New capability or behaviour

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants